/*
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QRegExp>
#include "wakabaagent.h"
#include "log.h"
#include "components/chan.h"
#include "components/board.h"
#include "network/request.h"
#include "captchafetchers/captchafetcher.h"

namespace Wishmaster
{
	WakabaAgent::WakabaAgent(const QString& host) : DefaultAgent(host),
		m_host(host)
	{
	}

	WakabaAgent::~WakabaAgent()
	{
	}

	void WakabaAgent::makePost(const PostDescriptor& post, const QString& captcha)
	{
		QString wakabascript = property("wakabascript").toString();
		wakabascript.replace("%BOARD%", post.board);

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, wakabascript, "POST");
		request->addPostField("task", "post");
		request->addPostField("parent", post.parent_thread.threadStringId());
		request->addPostField("name", "");
		request->addPostField(property("field1name").toString(), post.name);
		request->addPostField("link", "");
		request->addPostField(property("field2name").toString(), post.email);
		request->addPostField(property("field3name").toString(), post.topic);
		request->addPostField(property("field4name").toString(), post.text);
			addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "file");
//		if(post.attachments.count() == 0)
//			request->addPostField("nofile", "1");
		if(captchaFetcher()->id() == "generic")
			request->addPostField("captcha", captcha);
		request->addPostField("postredir", "1");
		request->addPostField("password", post.password);

		if(!captcha.isEmpty())
			captchaFetcher()->processRequest(post, captcha, request);

		QString referer = QString("http://%1%2res/%3.html").arg(m_host).arg(post.board).arg(post.parent_thread.threadNumericId());
		request->setReferer(referer);
		request->setProperty("thread_id", QVariant::fromValue<ThreadId>(post.parent_thread));

		connector()->connectRequest(this, SLOT(resultPost(RequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void WakabaAgent::createThread(const PostDescriptor& post, const QString& captcha)
	{
		QString wakabascript = property("wakabascript").toString();
		wakabascript.replace("%BOARD%", post.board);

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, wakabascript, "POST");
		request->addPostField("task", "post");
		request->addPostField("name", "");
		request->addPostField(property("field1name").toString(), post.name);
		request->addPostField("link", "");
		request->addPostField(property("field2name").toString(), post.email);
		request->addPostField(property("field3name").toString(), post.topic);
		request->addPostField(property("field4name").toString(), post.text);
		addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "file");
		request->addPostField("postredir", "1");
		if(captchaFetcher()->id() == "generic")
			request->addPostField("captcha", captcha);
		request->addPostField("password", post.password);
		QString referer = QString("http://%1%2").arg(m_host).arg(post.board);
		request->setReferer(referer);

		if(!captcha.isEmpty())
			captchaFetcher()->processRequest(post, captcha, request);

		request->setProperty("thread_id", QVariant::fromValue(post.parent_thread));

		connector()->connectRequest(this, SLOT(resultPost(RequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void WakabaAgent::deleteThread(const ThreadId& threadId, const QString& password)
	{
		QString referer = QString("http://%1%2wakaba.html").arg(m_host).arg(threadId.boardId());
		QString wakabascript = property("wakabascript").toString();
		wakabascript.replace("%BOARD%", threadId.boardId());

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, wakabascript, "POST");
		request->addPostField("delete", threadId.threadStringId());
		request->addPostField("task", "delete");
		request->addPostField("password", password);

		connector()->connectRequest(this, SLOT(resultDelete(HttpRequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void WakabaAgent::deletePost(const PostId& postId, const QString& password)
	{
		QString referer = QString("http://%1%2res/%3.html").arg(m_host).arg(postId.board()).arg(postId.threadId());
		QString wakabascript = property("wakabascript").toString();
		wakabascript.replace("%BOARD%", postId.board());

		HttpRequestPtr request = connector()->makeHttpRequest(m_host, wakabascript, "POST");
		request->addPostField("delete", QString::number(postId.postId()));
		request->addPostField("task", "delete");
		request->addPostField("password", password);

		connector()->connectRequest(this, SLOT(resultDelete(HttpRequestPtr, const QByteArray&)), 0, request);
		connector()->queue(request);
	}

	void WakabaAgent::resultPost(const RequestPtr& r, const QByteArray& data)
	{
		ThreadId threadId = r->property("thread_id").value<ThreadId>();
		QString regexp = QString::fromUtf8("<h1 style=\"text-align: center\">\\w+: ([^<>]*)");
		QRegExp rx(regexp);
		if(rx.indexIn(QString::fromUtf8(data)) != -1)
		{
			log(llDebug, "Error: %s", qPrintable(rx.cap(1)));
			emit postingError(rx.cap(1));
			return;
		}
		else
		{
			//emit postingError("");
			// TODO we can emit here 'thread' slot as well
		}
		log(llDebug, "board: %s, thread: %d", qPrintable(threadId.boardId()), threadId.threadNumericId());
		emit postingDone(threadId);
		//emit refresh(m_board, m_threadID, true);
	}

	void WakabaAgent::resultDelete(const HttpRequestPtr& /* r */, const QByteArray& /* data */)
	{
		// Vsem pohui
	}

	QStringList WakabaAgent::ratings()
	{
		return QStringList();
	}

	ChanAgent* WakabaAgent::clone(const QString& host)
	{
		return new WakabaAgent(host);
	}

	QString WakabaAgent::id()
	{
		return "wakaba";
	}
}

Q_EXPORT_PLUGIN2(wakabaagent, Wishmaster::WakabaAgent)

